package com.hfxt.advice;


import com.hfxt.service.impl.UserServiceImpl;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

import java.util.Arrays;

//日志增强处理类
public class LoggerAdvice {
    //创建日志对象
    private static Logger logger = Logger.getLogger(UserServiceImpl.class);

    //前置方法
    public void before(JoinPoint jp) {
        logger.info("调用" + jp.getTarget() + "的" + jp.getSignature().getName() + "方法，方法的入参是" + Arrays.toString(jp.getArgs()));
    }

    //后置方法
    public void afterReturnning(JoinPoint jp, Object result) {
        logger.info("调用" + jp.getTarget() + "的" + jp.getSignature().getName() + "方法，方法的返回值是" + result);
    }

    //异常增强 只有发生异常的时候才会执行
    public void afterThrowing(JoinPoint jp, RuntimeException e) {
        logger.info("调用" + jp.getTarget() + "的" + jp.getSignature().getName() + "方法，方法发生异常是" + e.getMessage());
    }

    //最终增强 发生异常的时候也会执行
    public void after(JoinPoint jp) {
        logger.info("调用" + jp.getTarget() + "的" + jp.getSignature().getName() + "方法，方法执行结束");
    }

    public Object around(ProceedingJoinPoint jp) throws Throwable {
        logger.info("调用" + jp.getTarget() + "的" + jp.getSignature().getName() + "方法，方法的入参是" + Arrays.toString(jp.getArgs()));
        Object result = null;
        try {
            result = jp.proceed();
            logger.info("调用" + jp.getTarget() + "的" + jp.getSignature().getName() + "方法，方法的返回值是" + result);

        } catch (Exception e) {
            logger.info("调用" + jp.getTarget() + "的" + jp.getSignature().getName() + "方法，方法发生异常是" + e.getMessage());

        }
        return result;
    }
}
